<?php


namespace app\common\service\system;

use app\common\model\agent\PromotionBillModel;
use app\common\model\Merchant\MerchantModel;
use app\common\model\order\ShopOrderModel;
use app\common\model\promotion\PromotionUserModel;
use app\common\service\order\ShopOrderService;
use app\common\service\promotion\PromotionUserService;
use DateTime;
use think\facade\Db;
use app\common\cache\Cache;
use app\common\service\system\UserService;
use hg\apidoc\annotation as Apidoc;

/**
 * 控制台
 */
class IndexService
{
    /**
     * 首页
     *
     * @return array
     */
    public static function index()
    {
        $data['name']   = 'Admin';
        $data['desc']   = '基于ThinkPHP8和Vue3的百亿补贴管理系统';
        return $data;
    }

    /**
     * 查询总后台首页数据
     * @Author: 易军辉
     * @DateTime:2024-11-14 20:30
     */
    public static function getAdminDashboard($where)
    {
        /*******************************用户、商家、用户访问量、活跃用户*******************************/
        $sta_date_7 = date('Y-m-d 00:00:00', strtotime('-6 days'));
        $end_date_7 = date('Y-m-d 23:59:59');
        //用户
        $member_info = ['date_list'=>[],'value_list'=>[]];
        $member = Db::query("SELECT 
                            date_format(create_time,'%Y-%m-%d') as date,
                            count(member_id) as num
                            from ya_member
                            where 
                            is_delete=0 
                            and is_disable =0
                            and create_time BETWEEN '".$sta_date_7."' AND '".$end_date_7."'
                            GROUP BY date_format(create_time,'%Y-%m-%d')");
        //商家
        $mer_info = ['date_list'=>[],'value_list'=>[]];
        $mer = Db::query("SELECT 
                            date_format(create_time,'%Y-%m-%d') as date,
                            count(id) as num
                            from ya_merchant
                            where 
                            is_delete=0 
                            and is_disable =0
                            and create_time BETWEEN '".$sta_date_7."' AND '".$end_date_7."'
                            GROUP BY date_format(create_time,'%Y-%m-%d')");
        //用户访问量
        $visit_info = ['date_list'=>[],'value_list'=>[]];
        $visit = Db::query("SELECT 
                            date_format(create_time,'%Y-%m-%d') as date,
                            count(log_id) as num
                            from ya_member_log
                            where 
                            is_delete=0 
                            and create_time BETWEEN '".$sta_date_7."' AND '".$end_date_7."'
                            GROUP BY date_format(create_time,'%Y-%m-%d')");
        //活跃用户
        $active_info = ['date_list'=>[],'value_list'=>[]];
        $active = Db::query("SELECT 
                                DATE_FORMAT(DATE_ADD(create_time, INTERVAL - (HOUR(create_time) % 2) HOUR), '%Y-%m-%d %H:00') AS date,
                                COUNT(log_id) AS num
                            FROM 
                                ya_member_log
                            WHERE  DATE(create_time) = CURDATE()
                            GROUP BY 
                                DATE_FORMAT(DATE_ADD(create_time, INTERVAL - (HOUR(create_time) % 2) HOUR), '%Y-%m-%d %H:00')
                            ORDER BY 
                                DATE_FORMAT(DATE_ADD(create_time, INTERVAL - (HOUR(create_time) % 2) HOUR), '%Y-%m-%d %H:00') ASC");
        // 创建初始时间对象
        $activeDateTime = new DateTime(date('Y-m-d 00:00'));
        // 设置格式化时间格式
        $format = 'Y-m-d H:i';
        // 根据 $count 数量循环生成时间
        for ($i = 0; $i < 12; $i++) {
            // 添加当前时间到结果数组
            $a_date_time = $activeDateTime->format($format);
            $active_info['date_list'][] = $a_date_time;
            // 增加时间间隔
            $activeDateTime->modify("+2 hours");
            //活跃用户
            $active_info['value_list'][$i] =0;
            foreach ($active as $key=>$val){
                if($val['date'] == $a_date_time){
                    $active_info['value_list'][$i] =$val['num'];
                }
            }
        }

        $dates_7 = [];
        $s_time_7 = strtotime($sta_date_7);
        $e_time_7 = strtotime($end_date_7);
        while ($s_time_7 <= $e_time_7) {
            $dates_7[] = date('Y-m-d', $s_time_7);
            $s_time_7 = strtotime('next day', $s_time_7);
        }
        foreach ($dates_7 as $k=>$v){
            //用户
            $member_info['value_list'][$k] =0;
            foreach ($member as $key=>$val1){
                if($val1['date'] == $v){
                    $member_info['value_list'][$k] =$val1['num'];
                }
            }
            //商家
            $mer_info['value_list'][$k] =0;
            foreach ($mer as $key=>$val2){
                if($val2['date'] == $v){
                    $mer_info['value_list'][$k] =$val2['num'];
                }
            }
            //访问量
            $visit_info['value_list'][$k] =0;
            foreach ($visit as $key=>$val3){
                if($val3['date'] == $v){
                    $visit_info['value_list'][$k] =$val3['num'];
                }
            }
        }
        $member_info['date_list'] = $dates_7;
        $mer_info['date_list'] = $dates_7;
        $visit_info['date_list'] = $dates_7;
        /*******************************订单统计*******************************/
        $statistics = ShopOrderService::adminDashboardStatistics($where);
        return compact('member_info','mer_info','visit_info','active_info','statistics');
    }

    /**
     * 总数统计
     * @Apidoc\Returned("count", type="array", children={
     *   @Apidoc\Returned("name", type="string", desc="名称"),
     *   @Apidoc\Returned("count", type="int", desc="总数")
     * })
     * @return array
     */
    public static function count()
    {
        $uid = user_id();
        $key = 'statistic:count' . $uid;
        $data = Cache::get($key);
        if (empty($data)) {
            $count = [];
            $table = [
                ['table' => 'member', 'name' => '会员', 'menu_url' => 'admin/member.Member/list'],
                // ['table' => 'member_tag', 'name' => '会员标签', 'menu_url' => 'admin/member.Tag/list'],
                // ['table' => 'member_group', 'name' => '会员分组', 'menu_url' => 'admin/member.Group/list'],
                // ['table' => 'member_api', 'name' => '会员接口', 'menu_url' => 'admin/member.Api/list'],
                ['table' => 'content', 'name' => '内容', 'menu_url' => 'admin/content.Content/list'],
                // ['table' => 'content_category', 'name' => '内容分类', 'menu_url' => 'admin/content.Category/list'],
                // ['table' => 'content_tag', 'name' => '内容标签', 'menu_url' => 'admin/content.Tag/list'],
                ['table' => 'file', 'name' => '文件', 'menu_url' => 'admin/file.File/list'],
                // ['table' => 'file_group', 'name' => '文件分组', 'menu_url' => 'admin/file.Group/list'],
                // ['table' => 'file_tag', 'name' => '文件标签', 'menu_url' => 'admin/file.Tag/list'],
                ['table' => 'setting_carousel', 'name' => '轮播', 'menu_url' => 'admin/setting.Carousel/list'],
                ['table' => 'setting_notice', 'name' => '通告', 'menu_url' => 'admin/setting.Notice/list'],
                ['table' => 'setting_accord', 'name' => '协议', 'menu_url' => 'admin/setting.Accord/list'],
                ['table' => 'setting_feedback', 'name' => '反馈', 'menu_url' => 'admin/setting.Feedback/list'],
                ['table' => 'setting_region', 'name' => '地区', 'menu_url' => 'admin/setting.Region/list'],
                // ['table' => 'setting_link', 'name' => '友链', 'menu_url' => 'admin/setting.Link/list'],
                // ['table' => 'system_menu', 'name' => '菜单', 'menu_url' => 'admin/system.Menu/list'],
                // ['table' => 'system_role', 'name' => '角色', 'menu_url' => 'admin/system.Role/list'],
                // ['table' => 'system_user', 'name' => '用户', 'menu_url' => 'admin/system.User/list'],
                // ['table' => 'system_dept', 'name' => '部门', 'menu_url' => 'admin/system.Dept/list'],
                // ['table' => 'system_post', 'name' => '职位', 'menu_url' => 'admin/system.Post/list'],
                // ['table' => 'system_notice', 'name' => '公告', 'menu_url' => 'admin/system.Notice/list'],
            ];

            $user = UserService::info($uid, false);
            foreach ($table as $v) {
                if (in_array($v['menu_url'], $user['roles'] ?? [])) {
                    $where = [];
                    $where = [where_delete()];
                    if ($v['table'] == 'setting_region') {
                        $where[] = ['region_level', '<=', config('admin.region_level', 3)];
                    }

                    $temp = [];
                    $temp['name']  = $v['name'];
                    $temp['count'] = Db::name($v['table'])->where($where)->count();
                    $count[] = $temp;
                }
            }
            $data['count'] = $count;
            Cache::set($key, $data, 3600);
        }

        return $data;
    }

    /**
     * 查询首页数据
     * @Author: 易军辉
     * @DateTime:2024-07-22 10:50
     */
    public static function getDashboard()
    {
        $result = [];
        $uid = promotion_user_id();
        $model = new PromotionUserModel();
        $pk = $model->getPk();
        $info = $model->find($uid);
        if (empty($info)) {
            exception('系统繁忙，请稍后再试');
        }
        $result['date'] = date('Y-m-d H:i:s');
        /******************************提成比例*********************************************/
        $result['commission_ratio']= $info['commission_ratio'];
        /******************************直属商家*********************************************/
        $merchant = MerchantModel::where('promotion_user_id',$info[$pk])
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->field('id')
            ->select()
            ->toArray();
        //商家数量
        $result['merchant_count']=count($merchant);
        //今日收益
        $result['todays_earnings']=PromotionBillModel::where('promotion_user_id',$uid)
        ->where('type',PromotionBillModel::getTypes('commission',1))
        ->where('is_disable',0)
        ->where('is_delete',0)
        ->whereBetween('create_time', [date('Y-m-d')." 00:00:00", date('Y-m-d')." 23:59:59"])
        ->sum('money');
        $result['todays_earnings']=bcmul($result['todays_earnings'], 1,2);
        //累计收益
        $result['total_earnings']=$info['income'];
        //商家id
        $merchant_ids = array_column($merchant,'id');
        $order =  self::getOrderNum($merchant_ids);
        $result['total_num'] = $order['total_num']??0;
        $result['orders_today'] = $order['orders_today']??0;
        $result['orders_yesterday'] = $order['orders_yesterday']??0;
        $result['orders_last_7_days'] = $order['orders_last_7_days']??0;
        $result['success_num'] = $order['success_num']??0;
        $result['revoke_num'] = $order['revoke_num']??0;
        //查询推广员所有下级
        $promotion_user = PromotionUserService::getAllDescendants($info[$pk]);
        $result['promotion_user_count'] = count($promotion_user);
        if(!$promotion_user){
            $promotion_user =[0];
        }
        $c_merchant = MerchantModel::whereIn('promotion_user_id',$promotion_user)
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->field('id')
            ->select()
            ->toArray();
        $c_merchant_ids = array_column($c_merchant,'id');
        $c_order =  self::getOrderNum($c_merchant_ids);
        $result['c_total_num'] = $c_order['total_num']??0;
        $result['c_orders_today'] = $c_order['orders_today']??0;
        $result['c_orders_yesterday'] = $c_order['orders_yesterday']??0;
        $result['c_orders_last_7_days'] = $c_order['orders_last_7_days']??0;
        $result['c_success_num'] = $c_order['success_num']??0;
        $result['c_revoke_num'] = $c_order['revoke_num']??0;
//        //下级累计赚取
//        $money = PromotionBillModel::whereIn('promotion_user_id',$promotion_user)
//            ->where('type',PromotionBillModel::getTypes('commission',1))
//            ->where('is_disable',0)
//            ->where('is_delete',0)
//            ->sum('money');
//        $result['c_money'] = $money??0;
        return $result;
    }

    /**
     * 查询订单数
     * @Author: 易军辉
     * @DateTime:2024-07-24 20:21
     * @param $merchant_ids
     */
    private static function getOrderNum($merchant_ids=[])
    {
        $c_merchant_str =0;
        if($merchant_ids){
            $c_merchant_str = implode(',',$merchant_ids);
        }
        $success_status = ShopOrderModel::getStatus('o_success',1);
        $revoke_status = ShopOrderModel::getStatus('o_revoke',1);
        $sql = <<<SQL
                SELECT
                  -- 统计 总订单数
                  count(id) as total_num,
                  -- 统计 今日 内订单数量  
                  SUM(CASE WHEN create_time >= CURDATE()  THEN 1 ELSE 0 END) AS orders_today,
                  -- 统计 昨天订单数量
                  SUM(CASE WHEN create_time >= DATE_SUB(NOW(), INTERVAL 2 DAY) AND create_time <= DATE_SUB(NOW(), INTERVAL 1 DAY) THEN 1 ELSE 0 END) AS orders_yesterday,  
                  -- 统计 7 天内订单数量
                  SUM(CASE WHEN create_time >= NOW() - INTERVAL 7 DAY THEN 1 ELSE 0 END) AS orders_last_7_days, 
                  SUM(CASE WHEN status = {$success_status} THEN 1 ELSE 0 END) AS success_num,
                  SUM(CASE WHEN status = {$revoke_status} THEN 1 ELSE 0 END) AS revoke_num
                FROM
                  ya_shop_order
                WHERE
                    is_delete=0 AND merchant_id IN({$c_merchant_str})
        SQL;
        $order =  Db::query($sql);
        return $order[0];
    }

    /**
     * 查询待受理事务
     * @Author: 易军辉
     * @DateTime:2024-11-18 15:15
     */
    public static function getMsgNum()
    {
        $sql = <<<SQL
                SELECT 
                    SUM(count) AS total,
                    SUM(CASE WHEN type = 'member_account' THEN count END) AS member_account_num,
                    SUM(CASE WHEN type = 'member_auth' THEN count END) AS member_auth_num,
                    SUM(CASE WHEN type = 'goods' THEN count END) AS goods_num,
                    SUM(CASE WHEN type = 'mer_recharge' THEN count END) AS mer_recharge_num,
                    SUM(CASE WHEN type = 'mer_withdrawal' THEN count END) AS mer_withdrawal_num,
                    SUM(CASE WHEN type = 'promotion_withdrawal' THEN count END) AS promotion_withdrawal_num,
                    SUM(CASE WHEN type = 'member_withdrawal' THEN count END) AS member_withdrawal_num
                FROM (
                    SELECT 'member_account' AS type, COUNT(id) AS count 
                    FROM ya_member_account 
                    WHERE is_disable = 0 AND is_delete = 0 AND status = 0
                
                    UNION ALL
                
                    SELECT 'member_auth' AS type, COUNT(id) AS count 
                    FROM ya_member_id_card 
                    WHERE is_disable = 0 AND is_delete = 0 AND auth_status = 1
                
                    UNION ALL
                
                    SELECT 'goods' AS type, COUNT(id) AS count 
                    FROM ya_shop_product 
                    WHERE is_disable = 0 AND is_delete = 0 AND status = 1
                
                    UNION ALL
                
                    SELECT 'mer_recharge' AS type, COUNT(id) AS count 
                    FROM ya_merchant_recharge 
                    WHERE is_disable = 0 AND is_delete = 0 AND auth_status = 0
                
                    UNION ALL
                
                    SELECT 'mer_withdrawal' AS type, COUNT(id) AS count 
                    FROM ya_merchant_withdrawal 
                    WHERE is_disable = 0 AND is_delete = 0 AND auth_status = 0
                
                    UNION ALL
                
                    SELECT 'promotion_withdrawal' AS type, COUNT(id) AS count 
                    FROM ya_promotion_withdrawal 
                    WHERE is_disable = 0 AND is_delete = 0 AND auth_status = 0
                
                    UNION ALL
                
                    SELECT 'member_withdrawal' AS type, COUNT(id) AS count 
                    FROM ya_member_withdrawal 
                    WHERE is_disable = 0 AND is_delete = 0 AND auth_status = 0
                ) AS counts;
        SQL;
        $counts =  Db::query($sql);
        $count =$counts[0];
        return $count;
    }
}
